package top.kaoshanji.ch02;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketOption;
import java.net.StandardSocketOptions;
import java.nio.channels.NetworkChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Set;

/**
 * 代码清单 ch02-06：NetworkChannel示例(2.6.1节)
 * 输出互联网套接字地址在端口3080上所支持的选项，设置IP服务条款以及确认套接字通道上的SO_KEEPALIVE选项
 * author kaoshanji
 * ^_^
 * create time 2024/12/13 19:22
 */
public class NetworkChannelDemo {

    private static final Logger logger = LogManager.getLogger(NetworkChannelDemo.class);

    public static void main(String[] args) {
        logger.info("...代码清单 ch02-06：NetworkChannel示例(2.6.1节)...");

        SelectorProvider provider = SelectorProvider.provider();
        try {
            // 将NetworkChannel绑定到端口3080上
            NetworkChannel socketChannel = provider.openSocketChannel();
            SocketAddress address = new InetSocketAddress(3080);
            socketChannel = socketChannel.bind(address);

            // 检查套接字选项
            Set<SocketOption<?>> socketOptions = socketChannel.supportedOptions();
            System.out.println(socketOptions.toString());

            // 设置套接字的ToS(服务条款)选项
            socketChannel.setOption(StandardSocketOptions.IP_TOS, 3);

            // 获取 SO_KEEPALIVE 选项
            Boolean keepAlive = socketChannel.getOption(StandardSocketOptions.SO_KEEPALIVE);

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }


    }

}
